import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { svgBuilder } from "./src/plugin/icons/svgBuilder";
import ElementPlus from "unplugin-element-plus/vite";
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

function _resolve(dir) {
  return resolve(__dirname, dir);
}

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd());

  // 定义 Vue 特性标记
  const FEATURE_FLAGS = {
    __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true,
    __VUE_OPTIONS_API__: true,
  };
  
  // 开发环境直接代理到 natapp，生产环境使用 VITE_API_URL
  const apiTarget = mode === 'development'
    ? 'http://z78672cd.natappfree.cc/'  // 开发环境：natapp 地址
    : env.VITE_API_URL;  // 生产环境：使用环境变量

  // 开发环境打印代理配置
  if (mode === 'development') {
    console.log(`[vite] 开发服务器代理配置：
    - 本地地址：http://localhost:9001/api/*
    - 代理目标：${apiTarget}
    `);
  }

  return defineConfig({
    resolve: {
      alias: { "@": _resolve("src") },
    },
    publicDir: 'public',  // 确保静态文件正确服务
    define: FEATURE_FLAGS,  // 定义 Vue 特性标记
    plugins: [
      vue({
        template: {
          compilerOptions: {
            // 添加Vue编译选项
            isCustomElement: (tag) => tag.includes('-')
          }
        }
      }),
      ElementPlus({}),
      AutoImport({ resolvers: [ElementPlusResolver()] }),
      Components({ resolvers: [ElementPlusResolver()] }),
      svgBuilder("./src/plugin/icons/svg/"),
    ],
    server: {
      port: 9001,
      cors: true,
      host: "0.0.0.0",
      proxy: {
        "/api": {
          target: apiTarget,
          changeOrigin: true,
          // 遇到不稳定的隧道/代理（如 natapp）时，允许不安全的 TLS 并增加超时以减少解析错误
          secure: false,
          proxyTimeout: 20000,
          timeout: 20000,
          // 保持请求主机头，必要时可以覆盖
          headers: {
            host: new URL(apiTarget).host
          },
          rewrite: (p) => p.replace(/^\/api/, ""),
          configure: (proxy, options) => {
            // 仅在开发模式下打印详细代理日志
            if (mode === "development") {
              proxy.on("error", (err, req, res) => {
                console.log(`[proxy error] ${req.method} ${req.url}`, err);
              });
              proxy.on("proxyReq", (proxyReq, req, res) => {
                console.log(`[proxy] ${req.method} ${req.url} -> ${apiTarget}`);
              });
              proxy.on("proxyRes", (proxyRes, req, res) => {
                console.log(`[proxy] ${req.method} ${req.url} <- ${proxyRes.statusCode}`);
              });
            }
          },
        },
      },
    },
  });
};
